package org.shangda.wechat.pet.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.power.common.util.DateTimeUtil;
import com.power.common.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 小程序接口工具类
 */
@Slf4j
public class WxMiniappUtil {

    /**
     * 用户登录小程序地址
     */
    private static String JSCODEURL = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";

    /**
     * 获取accessToken地址
     */
    private static String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";


    /**
     * 消息订阅发送地址
     */
    private static String MESSAGE_SUBSCRIBE_SEND_URL = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=%s";


    /**
     * 获取小程序码地址，适用于需要的码数量极多的业务场景 通过该接口生成的小程序码，永久有效，数量暂无限制。
     */
    public static final String GET_WXACODE_UNLIMIT_URL = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s";

    /**
     * 获取小程序码，适用于需要的码数量较少的业务场景。 通过该接口生成的小程序码，永久有效，有数量限制
     */
    public static final String GET_WXACODE_URL = "https://api.weixin.qq.com/wxa/getwxacode?access_token=%s";

    /**
     * 获取用户手机号
     */
    public static final String GET_USER_PHONE_NUMBER = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s";

    // jscode换取openid
    public static JSONObject jscodeToSession(String appId, String secret, String code){
        String response = HttpUtil.doGet(String.format(JSCODEURL, appId, secret, code));
        return JSON.parseObject(response);
    }

    /**
     * 获取token
     * @param appId
     * @param secret
     * @return
     */
    public static JSONObject getAccessToken(String appId, String secret){
        String response = HttpUtil.doGet(String.format(ACCESS_TOKEN_URL, appId, secret));
        return JSON.parseObject(response);
    }

    /**
     * 发送订阅消息
     * @param accessToken
     * @param touser
     * @param template_id
     * @param data
     * @param miniprogram_state
     * @return
     */
    public static JSONObject sendSubscribeMessage(String accessToken, String touser, String template_id, JSONObject data, String miniprogram_state, String detailPath){
        log.info("sendSubscribeMessage touser:{}, template_id:{}, data:{}, accessToken:{}, miniprogram_state : {}",touser, template_id, data, accessToken, miniprogram_state);
        JSONObject postData = new JSONObject();
        postData.put("touser", touser);
        postData.put("template_id", template_id);
        if(StringUtils.isNotBlank(detailPath)) {
            postData.put("page", detailPath);
        }
        if(StringUtils.isNotBlank(miniprogram_state)) {
            postData.put("miniprogram_state", miniprogram_state);
        }
        postData.put("data", data);
        log.info(postData.toJSONString());
        String response = HttpUtil.doPostJson(String.format(MESSAGE_SUBSCRIBE_SEND_URL, accessToken), postData);
        log.info("sendSubscribeMessage : {}", response);
        return JSON.parseObject(response);
    }

    /**
     * 获取无限制小程序码
     * @param sceneStr
     * @param page
     * @param filePath
     * @param uploadDomainUrl
     * @return 生成成功的小程序码http访问路径
     */
    public static String getWxacodeUnlimit(String sceneStr, String page, String filePath, String uploadDomainUrl, String accessToken,Integer width){
        return getWxacode(sceneStr, page,filePath, uploadDomainUrl, true, accessToken, width);
    }

    /**
     * 获取有限制小程序码
     * @param page
     * @param filePath
     * @param uploadDomainUrl
     * @return 生成成功的小程序码http访问路径
     */
    public static String getWxacodeLimit(String page, String filePath, String uploadDomainUrl, String accessToken,Integer width){
        return getWxacode(null,page, filePath, uploadDomainUrl, false, accessToken, width);
    }

    /**
     * 从微信上获取小程序码
     * @param sceneStr 场景值 相当于参数值，不能太长否则无法生成小程序码，无限制小程序码生成时传递
     * @param page 扫码后跳转到的小程序页面， 可选 不填默认小程序首页
     * @param filePath 小程序码图片存放路径
     * @param uploadDomainUrl http访问目录
     * @param isUnlimit 是否有数量限制的小程序码,如果是没有限制的，需要传场景值 sceneStr
     * @return String
     * @throws Exception
     */
    private static String getWxacode(String sceneStr, String page, String filePath, String uploadDomainUrl, boolean isUnlimit, String accessToken, Integer width){
        try {
            String fileName = System.currentTimeMillis() + ".jpg";
            Map<String, Object> params = new HashMap<>();
            params.put("width", width);//二维码宽度
            String url = String.format(GET_WXACODE_URL, accessToken);
            if(isUnlimit){
                if(StringUtil.isNotEmpty(page)) {
                    params.put("page", page);//要跳转的页面,正式发布后才能传值
                }
                params.put("scene", sceneStr);//参数
                url = String.format(GET_WXACODE_UNLIMIT_URL, accessToken);
            }else {
                params.put("path", page);
            }

            CloseableHttpClient httpClient = HttpClientBuilder.create().build();

            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
            String body = JSON.toJSONString(params);
            StringEntity entity;

            entity = new StringEntity(body);
            entity.setContentType("image/png");
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);
            if(!response.getEntity().isStreaming()){
                log.error("getWxacode exception:{}", EntityUtils.toString(response.getEntity(), "UTF-8"));
                return null;
            }

            File targetFile = new File(filePath);
            if(!targetFile.exists()){
                targetFile.mkdirs();
            }
            try(InputStream inputStream = response.getEntity().getContent();
                FileOutputStream out = new FileOutputStream(new File(filePath,fileName))) {
                byte[] buffer = new byte[8192];
                int bytesRead = 0;
                while((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
                out.flush();
            }

            return uploadDomainUrl + fileName;
        } catch (Exception e) {
            log.error("getWxacode exception:", e);
            return null;
        }
    }

    /**
     * 获取用户手机号
     * @param accessToken
     * @return
     */
    public static JSONObject getUserPhoneNumber(String accessToken, String code){
        log.info("getUserPhoneNumber accessToken : {}, code : {}", accessToken, code);
        JSONObject params = new JSONObject();
        params.put("code", code);
        String response = HttpUtil.doPostJson(String.format(GET_USER_PHONE_NUMBER, accessToken), params);
        log.info("getUserPhoneNumber response : {}", response);
        return JSON.parseObject(response);
    }

    public static void main(String[] args) throws Exception{
        /*JSONObject jsonObject = getAccessToken("wx3c67d724636c6356", "f272fa040b7764625e67b47ea5e450c6");
        System.out.println(jsonObject.toJSONString());*/

        /*String accessToken = "35_d5MYUM_pQohyQ7wMEMnmmgOzGY_bYfy5jEb-bDWqfGmnt0VtLWdkNDqR-RDHB6Zu0PGFoxon7Qfg7wtgUfZjzOxlY73-VN6nvorHNWtecTqD-dNal3T5oT5Fg1g9ieEOOuyDZM7t0utVIQdAYSHeAAALFU";
        JSONObject data = new JSONObject();
        Map<String, String > dataMap = new HashMap<>();
        dataMap.put("value", "DEV2020073013524094704039669");
        data.put("character_string1", dataMap);
        Map<String, String > dataMap2 = new HashMap<>();
        dataMap2.put("value", "Palace Skateboards");
        data.put("thing2", dataMap2);
        Map<String, String > dataMap3 = new HashMap<>();
        dataMap3.put("value", "1.02");
        data.put("amount3", dataMap3);
        JSONObject timeValJO = new JSONObject();
        timeValJO.put("value", DateTimeUtil.nowStrTime());
        data.put("time4", timeValJO);
        Map<String, String > dataMap4 = new HashMap<>();
        dataMap4.put("value", "您的订单已支付成功，请点击进入小程序查看");
        data.put("thing5", dataMap4);*/

//        JSONObject jsonResult = sendSubscribeMessage(accessToken, "oHuop43FdaMZprHmaeyPLPOe8pDk", "N34uHKKRMxSUmA3umieLU4fR_HnygJiq89fVcCkLHq8", data, "trial");
//        System.out.println(jsonResult.toJSONString());
//        System.out.println(data.toJSONString());

        String filePath = "./data/imgs/";
        String accessToken = "49_VJU7bi4xseQIzV4PnMBvUfy2aohJkSgq5mrfQWxNzMY09mqwO9F62HxDKJO0iBehnZp8-SGbIMByG0u1uK6mPTD505qXZaPZXx0VN7neiLrBTKMLuvLYfETngVoF3ttRQMbhbBctmE6xydRHGSOaABAUGC";
        System.out.println(getWxacodeUnlimit("id=1",
                "pages/note-detail/note-detail",
                filePath,
                "https://dev.d1m.cn/", accessToken, 312));
    }
}
